package com.origin.oss.solution.huawei.config;

import cn.hutool.core.text.CharPool;
import com.obs.services.ObsClient;
import com.origin.oss.constant.OssConstant;
import com.origin.oss.solution.huawei.HuaweiOssClient;
import com.origin.oss.solution.huawei.ObsProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

/**
 * @author yezh
 * @date 2024/2/22 19:11
 */
@ConditionalOnClass(ObsClient.class)
@ConditionalOnProperty(prefix = OssConstant.OSS, name = OssConstant.OssType.HUAWEI + CharPool.DOT + OssConstant.ENABLE
        , havingValue = OssConstant.DEFAULT_ENABLE_VALUE)
@Configuration
@EnableConfigurationProperties(ObsProperties.class)
public class ObsConfiguration {

    @Bean
    public HuaweiOssClient huaweiOssClient(ObsProperties obsProperties) {
        ObsConfig obsConfig = obsProperties.getObsConfig();
        return new HuaweiOssClient(obsClient(obsConfig), obsConfig);
    }

    public ObsClient obsClient(ObsConfig obsConfig) {
        ObsClientConfig clientConfig = Optional.ofNullable(obsConfig.getClientConfig()).orElse(new ObsClientConfig());
        com.obs.services.ObsConfiguration obsConfiguration = clientConfig.toClientConfig();
        obsConfiguration.setEndPoint(obsConfig.getEndPoint());
        return new ObsClient(obsConfig.getAccessKey(), obsConfig.getSecretKey(), obsConfiguration);
    }

}
